package com.example.jin.myapplication.beatbox;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jin on 2016/6/18.
 */
public class BeatBox {
    //BeatBox is Non-Stashable
    private AssetManager mManager;
    private String PATH="sample";
    private String[] mFileList;
    private List<Sound> mSoundList;
    SoundPool mSoundPool;
    public BeatBox(Context context)
    {
        mSoundList=new ArrayList<>();
        mManager=context.getAssets();
        mSoundPool=null;
        mSoundPool= new SoundPool(5, AudioManager.STREAM_MUSIC,0);
        try {
            mFileList=mManager.list(PATH);
            for(String file:mFileList){
                String path=PATH+"/"+file;
                Sound sound=new Sound(path);
                mSoundList.add(sound);
                loadSound(sound);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public List<Sound> getSoundList(){
        return mSoundList;
    }
    public void loadSound(Sound sound){
        //InputStream is=mManager.open(sound.getPath());
        try {
            AssetFileDescriptor fd=mManager.openFd(sound.getPath());
            int f=mSoundPool.load(fd,1);
            sound.setFd(f);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void play(Sound sound){
        if(sound.getFd()==null){
            loadSound(sound);
        }
        if(sound.getFd()!=null){
            Log.i("main","fd is not null");
            mSoundPool.play(sound.getFd(),1,1,1,0,1);
        }
        else{
            Log.i("main","fd is null");
        }
    }
    public void release(){
        mSoundPool.release();
    }
}
